package cn.acewill.yxd.yunxundian.componet.menology;

import android.content.Context;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.xutils.DbManager;
import org.xutils.ex.DbException;
import org.xutils.x;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Map;

import cn.acewill.yxd.yunxundian.YXDAPP;
import cn.acewill.yxd.yunxundian.model.Schedule;
import cn.acewill.yxd.yunxundian.ui.MainActivity;

/**
 * Created by Jimmy on 2016/10/6 0006.
 */
public class CalendarUtils {

    protected  static YXDAPP yxdapp=new YXDAPP();
    protected static DbManager db = x.getDb(yxdapp.getDaoConfig());
    public static CalendarUtils sUtils;
    private static Map<String, int[]> sAllHolidays;
    private static List<Schedule> schRestList=new ArrayList<>();
    private static List<Schedule> schWorkList=new ArrayList<>();
    /*某一天周几*/
    private int dayOfWeek = 0;
    //一个月多少天,上月是第几天，下月的天数
    private int monthDays;
    private int weekDay;
    private int nextDay;
    private Schedule banSchList= null;
    private Schedule restList=null;


    public static synchronized CalendarUtils getInstance(Context context) {
        if (sUtils == null) {
            sUtils = new CalendarUtils();
            initAllHolidays(context);
        }
        return sUtils;
    }


    /*读hoilday数据*/
    private static void initAllHolidays(Context context) {
        try {

            InputStream is = context.getAssets().open("holiday.json");
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            int i;
            while ((i = is.read()) != -1) {
                baos.write(i);
            }
            initAllMyHolidays(context);
            sAllHolidays = new Gson().fromJson(baos.toString(), new TypeToken<Map<String, int[]>>() {
            }.getType());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void initAllMyHolidays(Context context){
        String[] jiaqi={"年假","休息","其他假"};
        try {
            if(schRestList!=null)
                schRestList.clear();
            schRestList=db.selector(Schedule.class).where("title","in",jiaqi).and("toUserId", "=", MainActivity.id).findAll();
            if(schWorkList!=null)
                schWorkList.clear();
            schWorkList=db.selector(Schedule.class)
                    .where("title","!=","休息")
                    .and("title","!=","年假")
                    .and("title","!=","其他假")
                    .and("toUserId", "=", MainActivity.id)
                    .findAll();
        } catch (DbException e) {
            e.printStackTrace();
        }
//        for (int i=0;i<sch.size();i++){
//            if (sch.get(i).getTitle().equals("年假")||
//                    sch.get(i).getTitle().equals("休息")||
//                    sch.get(i).getTitle().equals("其他假")){
//                schRestList.add(sch.get(i));
//            }else{
//                schWorkList.add(sch.get(i));
//            }
//        }

    }



    /**
     * 通过年份和月份 得到当月的日子
     *
     * @param year
     * @param month
     * @return
     */
    public static int getMonthDays(int year, int month) {
        month++;
        switch (month) {
            case 1:
            case 3:
            case 5:
            case 7:
            case 8:
            case 10:
            case 12:
                return 31;
            case 4:
            case 6:
            case 9:
            case 11:
                return 30;
            case 2://闰年
                if (((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0)) {
                    return 29;
                } else {
                    return 28;
                }
            default:
                return -1;
        }
    }

    /**
     * 返回当前月份1号位于周几
     *
     * @param year  年份
     * @param month 月份，传入系统获取的，不需要正常的
     * @return 日：1		一：2		二：3		三：4		四：5		五：6		六：7
     */
    public static int getFirstDayWeek(int year, int month) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(year, month, 1);
        return calendar.get(Calendar.DAY_OF_WEEK);
    }

    /**
     * 获得两个日期距离几周
     *
     * @return
     */
    public static int getWeeksAgo(int lastYear, int lastMonth, int lastDay, int year, int month, int day) {
        Calendar lastClickDay = Calendar.getInstance();
        lastClickDay.set(lastYear, lastMonth, lastDay, 0, 0, 0);//set(int year, int month, int date, int hourOfDay, int minute,int second)
        int week = lastClickDay.get(Calendar.DAY_OF_WEEK) - 1;
        Calendar clickDay = Calendar.getInstance();
        clickDay.set(year, month, day, 0, 0, 0);
        //clickDay.getTimeInMillis()当前日期转换成毫秒进行计算
        if (clickDay.getTimeInMillis() > lastClickDay.getTimeInMillis()) {
            return (int) ((clickDay.getTimeInMillis() - lastClickDay.getTimeInMillis() + week * 24 * 3600 * 1000) / (7 * 24 * 3600 * 1000));
        } else {
            return (int) ((clickDay.getTimeInMillis() - lastClickDay.getTimeInMillis() + (week - 6) * 24 * 3600 * 1000) / (7 * 24 * 3600 * 1000));
        }
    }

    /**
     * 获得两个日期距离几个月
     *
     * @return
     */
    public static int getMonthsAgo(int lastYear, int lastMonth, int year, int month) {
        return (year - lastYear) * 12 + (month - lastMonth);
    }


    public static int getWeekRow(int year, int month, int day) {
        int week = getFirstDayWeek(year, month);
        Calendar calendar = Calendar.getInstance();
        calendar.set(year, month, day);
        int lastWeek = calendar.get(Calendar.DAY_OF_WEEK);//一周中的第几天
        if (lastWeek == 7)
            day--;
        return (day + week - 1) / 7;
    }

    /**
     * 根据国历获取假期
     *
     * @return
     */
    public static String getHolidayFromSolar(int year, int month, int day) {
        String message = "";
        if (month == 0 && day == 1) {
            message = "元旦";
        } else if (month == 1 && day == 14) {
            message = "情人节";
        } else if (month == 2 && day == 8) {
            message = "妇女节";
        } else if (month == 2 && day == 12) {
            message = "植树节";
        } else if (month == 3) {
            if (day == 1) {
                message = "愚人节";
            } else if (day >= 4 && day <= 6) {
                if (year <= 1999) {
                    int compare = (int) (((year - 1900) * 0.2422 + 5.59) - ((year - 1900) / 4));
                    if (compare == day) {
                        message = "清明节";
                    }
                } else {
                    int compare = (int) (((year - 2000) * 0.2422 + 4.81) - ((year - 2000) / 4));
                    if (compare == day) {
                        message = "清明节";
                    }
                }
            }
        } else if (month == 4 && day == 1) {
            message = "劳动节";
        } else if (month == 4 && day == 4) {
            message = "青年节";
        } else if (month == 4 && day == 12) {
            message = "护士节";
        } else if (month == 5 && day == 1) {
            message = "儿童节";
        } else if (month == 6 && day == 1) {
            message = "建党节";
        } else if (month == 7 && day == 1) {
            message = "建军节";
        } else if (month == 8 && day == 10) {
            message = "教师节";
        } else if (month == 9 && day == 1) {
            message = "国庆节";
        } else if (month == 10 && day == 11) {
            message = "光棍节";
        } else if (month == 11 && day == 25) {
            message = "圣诞节";
        }
        return message;
    }

    public static Date getFirstDayOfWeek(Date date) {
        Calendar c = new GregorianCalendar();
        c.setFirstDayOfWeek(Calendar.SUNDAY);
        c.setTime(date);
        c.set(Calendar.DAY_OF_WEEK, c.getFirstDayOfWeek()); // Monday
        return c.getTime();
    }
    public Date addDays(Date date,int addnum)
    {
        Calendar   calendar   =   new   GregorianCalendar();
        calendar.setTime(date);
        calendar.add(calendar.DATE,addnum);//把日期往后增加一天.整数往后推,负数往前移动
        Date retdate=calendar.getTime();   //这个时间就是日期往后推一天的结果
        return retdate;
    }

    /**
     * initAllHolidays初始化了holiday的数据
     * @param year
     * @param month
     * @return
     */

    public int[] getHolidays(int year, int month){
        int holidays[] = new int[42];
        String[] jiaqi={"年假","休息","其他假"};
        Date aa=new Date(year-1900,month-1,1);
        Date calFirstDay=getFirstDayOfWeek(aa);
        for(int i=0;i<holidays.length;i++) {
            Date TempcalFirstDay = addDays(calFirstDay, i);
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            // 指定一个日期
            String chazhaoDay = dateFormat.format(TempcalFirstDay);

            if(schWorkList!=null) {
                for (int a = 0; a < schWorkList.size(); a++) {
                    if (schWorkList.get(a).getSchStartTime().contains(chazhaoDay)) {
                        holidays[i] = 2;
                    }
                }
            }
            if(schRestList!=null) {
                for (int b = 0; b < schRestList.size(); b++) {
                    if (schRestList.get(b).getSchStartTime().contains(chazhaoDay)) {
                        holidays[i] = 1;
                    }
                }
            }
        }
//                banSchList = db.selector(Schedule.class).where("schStartTime","like",chazhaoDay+"%")
//                        .and("title","!=","年假")
//                        .and("title","!=","其他假")
//                        .and("title","!=","休息")
//                        .findFirst();
//                 restList=db.selector(Schedule.class).where("schStartTime","like",chazhaoDay+"%")
//                        .and("title","in",jiaqi).findFirst();
//            } catch (DbException e) {
//                e.printStackTrace();
//            }
//
//            if (banSchList!=null){
//                holidays[i]=2;
//            }else if (restList!=null){
//                holidays[i]=1;
//            }else{
//                holidays[i]=0;
//            }

//        }

        return holidays;
    }


    // 指定某年中的某月的第一天是星期几
    public int getWeekdayOfMonth(int year, int month) {
        Calendar cal = Calendar.getInstance();
        cal.set(year, month - 1, 1);
        dayOfWeek = cal.get(Calendar.DAY_OF_WEEK) - 1;
        return dayOfWeek;
    }

    public static int getMonthRows(int year, int month) {
        int size = getFirstDayWeek(year, month) + getMonthDays(year, month) - 1;
        return size % 7 == 0 ? size / 7 : (size / 7) + 1;//为o则size / 7，不为0则(size / 7) + 1；
    }

}

